package com.example.dormitoryscoresystem.util;



import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

public class WxCodeGenerator {

    // 替换为你的小程序 AppID 和 AppSecret
    private static final String APP_ID = "wxbce9eac24cabc29a";
    private static final String APP_SECRET = "0aaa16d3021d7f489df9e04bf504ce78";

    // 获取 access_token
    public static String getAccessToken() throws IOException {
        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential"
                + "&appid=" + APP_ID + "&secret=" + APP_SECRET;

        HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
        conn.setRequestMethod("GET");

        BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        StringBuilder response = new StringBuilder();
        String inputLine;

        while ((inputLine = in.readLine()) != null)
            response.append(inputLine);
        in.close();

        String result = response.toString();
        String token = result.split("\"access_token\":\"")[1].split("\"")[0];

        return token;
    }

    // 生成小程序码
    public static void generateWxCode(String sceneParam, String pagePath, String outputFilePath) throws Exception {
        String token = getAccessToken();

        String url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + token;
        URL obj = new URL(url);
        HttpURLConnection conn = (HttpURLConnection) obj.openConnection();

        conn.setRequestMethod("POST");
        conn.setDoOutput(true);

        // 构造请求体：scene 是你想传入页面的参数
        String json = String.format(
                "{\"scene\":\"%s\", \"page\":\"%s\", \"width\":430}",
                sceneParam, pagePath
        );

        OutputStream os = conn.getOutputStream();
        os.write(json.getBytes("UTF-8"));
        os.flush();
        os.close();

        // 返回的是图片数据
        InputStream in = conn.getInputStream();
        FileOutputStream out = new FileOutputStream(outputFilePath);
        byte[] buffer = new byte[4096];
        int len;
        while ((len = in.read(buffer)) != -1)
            out.write(buffer, 0, len);

        out.close();
        in.close();

        System.out.println("✅ 小程序码已生成：" + outputFilePath);
    }

    // 测试用 main 方法
    public static void main(String[] args) throws Exception {
        // 示例：跳转到 pages/score/score 页面，并传入参数 dorm123
        String scene = "";
        String page = "pages/score/score";  // 小程序的页面路径
        String outPath = "score_dorm1235.png";

        generateWxCode("", page, outPath);
    }
}

